import json

from django.shortcuts import render, redirect, reverse
from django.views.generic import View
from .forms import LoginForm, RegisterForm
from django.http import JsonResponse, HttpResponse
from django.contrib.auth import authenticate, login, logout
from utils import mcache, restful
from utils.alisms.demo_sms_send import send_sms
from io import BytesIO
from utils.captcha.captcha import Captcha
from .models import User


# Create your views here.
# 类视图  当一个页面上 既有 get 又有post
# def login(requst):
#     if requst.method == 'POST':
#         return 'post'
#     return 'get'
class LoginView(View):
    def get(self, request):
        return render(request, 'authPro/login.html')

    def post(self, request):
        # 实例化  self  ===== form
        form = LoginForm(request.POST)
        # cleaned_data 必须是通过form验证  cleaned_data 里面存放的是所有经过 Form
        # telephone = form.cleaned_data["telephone"]
        if form.is_valid():
            telephone = form.cleaned_data["telephone"]
            password = form.cleaned_data["password"]
            remember = form.cleaned_data["remember"]
            # print('='*20)
            # print(telephone)
            # print(password)
            # print(remember)
            # print('='*20)
            user = authenticate(username=telephone, password=password)
            if user:
                next_url = request.GET.get("next")
                if next_url:
                    return redirect(next_url)
                login(request, user)
                if remember:
                    # print(dir(request.session))
                    # None ===> 14 天  单位是秒
                    request.session.set_expiry(None)
                else:
                    # 浏览器 关闭就没了
                    request.session.set_expiry(0)
                    # 我们采用的是 ajax 所以说  redirect(reverse("news:index")) 无效
                    # 规范 {"code": 200, "msg":"", "data":[]}
                    # 规范 {"code": 400, "msg":"错误提醒", "data":{数据}}
                    # res["message"]  res["msg"]
                    #  规范 {"code": 400, "msg":"错误提醒", "data":{数据}}
                return restful.ok()
            return restful.params_error(message="用户名或密码错误")
        return restful.params_error(message=form.get_error())


def logout_view(request):
    logout(request)
    # 退出登陆后跳转到登录
    return redirect(reverse("news:index"))


class RegisterView(View):
    def get(self, request):
        return render(request, 'authPro/register.html')

    def post(self, request):
        form = RegisterForm(request.POST)
        # True and True
        if form.is_valid() and form.valid_data():
            telephone = form.cleaned_data.get("telephone")
            username = form.cleaned_data.get("username")
            password = form.cleaned_data.get("password")
            # User 自定义
            user = User.objects.create_user(telephone=telephone, username=username, password=password)
            # 注册完之后 login
            login(request, user)
            # {code: 0, message:"", data: null}
            # restful API风格/约定  PEP8
            return restful.result()
        return restful.params_error(message=form.get_error())


def send_sms_captcha(request):
    telephone = request.GET.get("telephone")
    print(telephone)
    captcha = Captcha.gene_text()
    # ret = send_sms(telephone, captcha)
    print("短信验证码 {}".format(captcha))
    mcache.set_key("sms_captcha", captcha)
    return restful.result(data={"sms_ret": "123"})


def graph_captcha(request):
    captcha, image = Captcha.gene_code()
    # 实例化 BytesIo
    out = BytesIO()
    # 是报存文件到 out 01010010101
    image.save(out, 'png')
    # 回到文件最开头的位置
    out.seek(0)

    response = HttpResponse(content_type="image/png")
    response.write(out.read())
    mcache.set_key("graph_captcha", captcha)
    return response
